package com.epoint.androidphone.mobileoa.ui.contacts;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.text.Html;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

import com.epoint.androidphone.R;
import com.epoint.androidphone.mobileoa.ui.superview.SuperPhonePage;
import com.epoint.androidmobile.bizlogic.syn.task.SynTask;
import com.epoint.androidmobile.core.control.ToastUtil;
import com.epoint.androidmobile.core.phoneutil.PhoneHelp;
import com.epoint.androidmobile.bizlogic.contacts.SearchContactsByPinyinTask;

/**
 * @author liyc
 * @time 2013-5-6 下午6:24:11
 * @annomation 通讯录
 */
public class ContactsListView extends SuperPhonePage {
	private ArrayList<String> backflaglist = new ArrayList<String>();;// 用作返回按钮作标记
	private long synTaskID,queryTaskID;
	private ListView lv;
	private List<Map<String, Object>> mData;
	private MyAdapter adapter;
	private EditText etCondition;
	private ImageView ivQuery;
	private int ENTER_FLAG;//2人员选择

	private List<Map<String, Object>> choosedPerson = new ArrayList<Map<String,Object>>();

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		addContentViewAndTitle(R.layout.contactslist_ws, getIntentViewTitle());
		getBtRight().setVisibility(View.VISIBLE);
		getBtRight().setText("同步");
		lv = (ListView) findViewById(R.id.lv);
		lv.setOnItemClickListener(this);
		lv.setOnItemLongClickListener(this);
		etCondition = (EditText) findViewById(R.id.etCondition);
		ivQuery = (ImageView) findViewById(R.id.ivQuery);
		ivQuery.setOnClickListener(this);
		mData = getData("");
		adapter = new MyAdapter(this);
		lv.setAdapter(adapter);

		ENTER_FLAG = getIntent().getIntExtra("enterflag", 0);
		if(ENTER_FLAG==2)
		{
			getTvTitle().setText("人员选择");
			getTvTitle().setOnClickListener(this);
			getBtRight().setText("确定");
		}
	}

	@Override
	public boolean onItemLongClick(AdapterView<?> parent, View view,
			int position, long id) {
		if(ENTER_FLAG!=2){
			if(parent.getId()==lv.getId()){
				if (mData.get(position).get("info").equals("人员")) {
					String mobile = mData.get(position).get("mobile").toString();
					if(mobile.equals("")){
						ToastUtil.toastWorning(this, "没有手机号码！");
					}
					else{
						PhoneHelp.Call(this, mobile);
					}
				}
			}
		}
		return super.onItemLongClick(parent, view, position, id);
	}

	@Override
	public void onItemClick(AdapterView<?> parent, View view,
			int position, long id) {
		if(parent.getId()==lv.getId()){

			if (mData.get(position).get("info").equals("部门")) {
				String deptTitle = mData.get(position).get("title").toString();
				backflaglist.add(mData.get(position).get("guid").toString());
				System.out.println(mData.get(position).get("guid").toString());
				mData = getData(mData.get(position).get("guid").toString());
				adapter.notifyDataSetChanged();
			} else {
				// 点击人员后操作
				if(ENTER_FLAG!=2){
					Intent intent = new Intent(this,
							ContactsDetailView.class);
					intent.putExtra("userguid", mData.get(position).get(
							"guid").toString());
					startActivity(intent);
				}
				else{
					System.out.println(parent.getChildCount());
				}
			}
		}

	}

	private List<Map<String, Object>> getData(String guid) {
		List<Map<String, Object>> list = dbUtil.getRootDeptMapReturn(0, guid);
		return list;
	}

	@Override
	public void onClick(View v) {
		if(v==getBtRight())
		{
			if(ENTER_FLAG==2)
			{
				String EnterClassName = getIntent().getStringExtra("EnterClassName");
				Class<?> EnterClass = null;
				try {
					EnterClass = Class.forName(EnterClassName);
				} catch (ClassNotFoundException e) {
					e.printStackTrace();
				}
				Intent intent = new Intent(this, EnterClass);
				String guids = "";
				String names = "";
				for(int i=0;i<choosedPerson.size();i++)
				{
					names += choosedPerson.get(i).get("name")+";";
					guids += choosedPerson.get(i).get("guid")+";";
				}
				intent.putExtra("guids", guids);
				intent.putExtra("names", names);
				setResult(RESULT_OK, intent);
				finish();

				return;
			}
			showDialogMiddle("正在同步数据...");
			HashMap<String, Object> param = getPassMap();
			param.put("ParentOUGuid", "");
			synTaskID = new SynTask(this, param).startTask();
		}
		else if(v==getIvLeft())
		{
			backLogic();
		}
		else if(v==ivQuery)
		{
			String tj = etCondition.getText().toString().trim().toLowerCase();// 查询条件
			if(tj.length()!=0){
				showTopProgressBar();
				Map<String, Object> param=new HashMap<String, Object>();
				param.put("tj", tj.toLowerCase());
				param.put("context", this);
				queryTaskID = new SearchContactsByPinyinTask(this, param).startTask();
				InputMethodManager imm = (InputMethodManager) getSystemService(INPUT_METHOD_SERVICE);
				imm.hideSoftInputFromWindow(etCondition.getWindowToken(), 0);
			}
		}
		else if(v==getTvTitle())
		{
			mData.clear();
			for(int i=0;i<choosedPerson.size();i++)
			{
				mData.add(choosedPerson.get(i));
			}
			adapter.notifyDataSetChanged();
		}
	}

	public void backLogic() {
		/**
		 * 返回按钮操作逻辑 liyc 2011.08.02
		 */
		if (backflaglist.size() == 0) {
			finish();
		} else if (backflaglist.size() == 1) {
			mData = getData("");
			adapter.notifyDataSetChanged();
		} else {
			mData = getData(backflaglist.get(backflaglist.size() - 2));
			adapter.notifyDataSetChanged();
		}

		if (backflaglist.size() > 0) {
			backflaglist.remove(backflaglist.size() - 1);
		}
	}

	@Override
	public void refreshUI(long taskId, Object obj) {
		super.refreshUI(taskId, obj);
		if(taskId==queryTaskID)
		{
			mData = (List<Map<String, Object>>) obj;
			adapter.notifyDataSetChanged();
		}
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		switch (keyCode) {
		case KeyEvent.KEYCODE_BACK:
			backLogic();
			break;
		}
		return false;
	}

	public final class ViewHolder {
		public ImageView img;
		public TextView title;
		public TextView info;
		public CheckBox cbPerson;
	}

	public class MyAdapter extends BaseAdapter {

		private LayoutInflater mInflater;

		public MyAdapter(Context context) {
			this.mInflater = LayoutInflater.from(context);
		}

		@Override
		public int getCount() {
			return mData.size();
		}

		@Override
		public Object getItem(int arg0) {
			return null;
		}

		@Override
		public long getItemId(int arg0) {
			return 0;
		}

		ViewHolder holder = null;

		@Override
		public View getView(final int position, View convertView,
				ViewGroup parent) {
			if (convertView == null) {
				holder = new ViewHolder();
				convertView = mInflater.inflate(R.layout.listviewwithbtnandimg,
						null);
				holder.img = (ImageView) convertView.findViewById(R.id.img);
				holder.title = (TextView) convertView.findViewById(R.id.title);
				holder.info = (TextView) convertView.findViewById(R.id.info);
				holder.cbPerson = (CheckBox) convertView
						.findViewById(R.id.cbPerson);

				convertView.setTag(holder);
			} else {
				holder = (ViewHolder) convertView.getTag();
			}
			final Map<String, Object> mp = mData.get(position);

			if(mp.get("info").equals("部门")){
				holder.cbPerson.setVisibility(View.INVISIBLE);
				holder.title.setTextColor(getResources().getColor(R.color.black));
				holder.img.setBackgroundResource(R.drawable.img_ou);
				holder.info.setVisibility(View.GONE);
			}
			else{
				holder.img.setBackgroundResource(R.drawable.img_user);
				holder.title.setTextColor(getResources().getColor(R.color.blue));
				if(ENTER_FLAG==2){
					holder.cbPerson.setVisibility(View.VISIBLE);
				}
				else{
					holder.cbPerson.setVisibility(View.INVISIBLE);
				}
				holder.info.setVisibility(View.VISIBLE);
			}

			if(ENTER_FLAG==2){
				holder.title.setText((String) mp.get("name"));
			}
			else{
				holder.title.setText((String) mp.get("title"));
			}
			holder.info.setText(Html.fromHtml("<font color='orange'>"+(String) mp.get("dp")+"</font>"));


			holder.cbPerson.setOnCheckedChangeListener(new OnCheckedChangeListener() {

				@Override
				public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {

					System.out.println(buttonView.getClass().getName());

					if(mp.get("info").equals("人员")){
						if(isChecked)
						{
							if(!choosedPerson.contains(mp)){
								choosedPerson.add(mp);
							}
						}
						else
						{
							if(choosedPerson.contains(mp)){
								choosedPerson.remove(mp);
							}
						}
					}
					getTvTitle().setText("人员选择("+choosedPerson.size()+")");
				}
			});

			if(choosedPerson.contains(mp))
			{
				holder.cbPerson.setChecked(true);
			}
			else{
				holder.cbPerson.setChecked(false);
			}
			return convertView;
		}
	}

}
